﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using ThuPhap.Class;
using System.Windows.Controls.Primitives;
using ThuPhap.Controls;

namespace ThuPhap.Facebook
{
    public partial class LogOutPage : PhoneApplicationPage
    {
        private const string ExtendedPermissions = "user_about_me,offline_access";
        private FacebookClient _fb;
        private string accessToken;
        private Popup popup;
        public LogOutPage()
        {
            InitializeComponent();
            popup = new Popup() { Child = new LoadingControl("Logouting ..."), IsOpen = true };
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string token;
            if (NavigationContext.QueryString.TryGetValue("token", out token))
            {
                this.accessToken = token;
            }
        }

        private void WebBrowser_Loaded(object sender, RoutedEventArgs e)
        {
            
            var parameters = new Dictionary<string, object>();
            parameters["next"] = "https://www.facebook.com/connect/login_success.html";
            parameters["access_token"] = this.accessToken;
            _fb = new FacebookClient(this.accessToken);
            BrowserControl.Navigate(_fb.GetLogoutUrl(parameters));
            
        }

        private void BrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
            {
                MessageBox.Show("Logout successfully!", "Notice", MessageBoxButton.OK);
                NavigationService.GoBack();
                SerializeHelper.DeleteToken();
                popup.IsOpen = false;
            }
        }

        private void BrowserControl_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            popup.IsOpen = false;
            MessageBox.Show("Not connect to internet", "Error", MessageBoxButton.OK);
            NavigationService.GoBack();
            
        }

        
    }
}